<template>
  <div class="app-container">
    <el-form :model="queryParams" :inline="true">
      <el-form-item prop="title" :label="$t('query.deviceImei')">
        <el-autocomplete v-model.trim="queryParams.deviceId"
                         :placeholder="$t('query.placeholder.deviceImei')"
                         class="inline-input"
                         :fetch-suggestions="queryDevice"
                         :trigger-on-focus="false"
                         style="width: 350px;"
                         :maxlength="80"
                         size="small">
        </el-autocomplete>
      </el-form-item>

      <el-form-item :label="$t('query.dateRange')">
        <el-date-picker
          v-model="dateRange"
          size="small"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="$t('query.placeholder.dateRange.start')"
          :end-placeholder="$t('query.placeholder.dateRange.end')"
          :clearable="false"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" v-hasPermi="['data:fault:query']" v-loading="loading" @click="handleQuery">
          {{this.$t('query.search')}}
        </el-button>
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          v-hasPermi="['data:fault:export']"-->
<!--          @click="handleExport">-->
<!--          {{this.$t('query.export')}}-->
<!--        </el-button>-->
      </el-form-item>

    </el-form>

    <el-table border v-loading="loading" :data="list" ref="table" :empty-text="$t('query.noData')">
      <el-table-column :label="$t('query.deviceCode')" align="center" prop="deviceId" width="250"></el-table-column>
      <el-table-column :label="$t('query.recordTime')" align="center" prop="recordTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('query.deviceTime')" align="center" prop="deviceTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deviceTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" width="660">
        <template slot-scope="scope" slot="header">
          {{$t('query.fault.faultData')}}
          <el-tooltip class="item" effect="dark" placement="top-start"
                      :content="$t('query.fault.faultContent')">
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span v-if="scope.row.faultData.length > 0">
             <span v-for="(item,index) in scope.row.faultData" class="content-tag">
                <el-tag type="success">
                  <span v-text="item"></span>
                </el-tag>
             </span>
          </span>
          <span v-else style="color: green;">无故障</span>
        </template>
      </el-table-column>

    </el-table>

    <el-row type="flex" justify="end">
      <el-col :span="3.5">
        <el-button-group>
          <el-button type="cyan" icon="el-icon-arrow-left" size="mini" :disabled="pageItems.length === 0"
                     @click="handlePrev">
            {{this.$t('query.prePage')}}
          </el-button>
          <el-button type="cyan" size="mini" :disabled="list.length < 10" @click="handleNext">
            {{this.$t('query.nextPage')}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
        </el-button-group>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import {fault} from "@/api/query/data"
import {getToken} from '@/utils/auth'
import {queryDeviceIdAsync} from '@/api/query/device'

export default {
  name: "index",
  data() {
    return {
      queryParams: {
        table: "keeway-fault-code",
        deviceId: null,
        types: "",
        from: new Date(),
        to: new Date(),
      },
      dateRange: [new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), new Date(new Date().getTime() + 3600 * 1000 * 24)],
      loading: false,
      source: null,

      list: [],
      pageItems: [],
    }
  },

  methods: {

    /** 搜索按钮操作 */
    handleQuery() {
      if (!this.validInput()) {
        return;
      }

      this.queryParams.from = this.dateRange[0].getTime();
      this.queryParams.to = this.dateRange[1].getTime();
      this.pageItems = [];
      this.loading = true;
      this.getList();
    },

    handlePrev() {
      if (!this.validInput()) {
        return;
      }
      this.loading = true;
      this.queryParams.to = this.pageItems.pop();
      this.getList();
    },

    handleNext() {
      if (!this.validInput()) {
        return;
      }
      this.loading = true;
      this.pageItems.push(this.list[0].deviceTime)
      this.queryParams.to = this.list[this.list.length - 1].deviceTime - 1
      this.getList();
    },

    getList() {
      fault(this.queryParams).then(rsp => {
        this.list = rsp.data;
        this.loading = false;
      })
    },

    queryDevice(suffix, cb) {
      let form = {deviceId: suffix, source: this.source}
      queryDeviceIdAsync(form, cb);
    },

    handleExport() {
      if (!this.validInput()) {
        return;
      }

      let table = this.$refs.table;
      let cols = table.$children.filter(it => {
        return it.prop !== null && it.prop !== undefined && it.label !== null && it.label !== undefined;
      });

      let props = cols.map(it => {
        return it.prop;
      }).join(",");

      let labels = cols.map(it => {
        return it.label;
      }).join(",")

      let path = "/query/data/export";

      const params = {
        table: this.queryParams.table,
        deviceId: this.queryParams.deviceId,
        from: this.dateRange[0].getTime(),
        to: this.dateRange[1].getTime(),
        Authorization: 'Bearer ' + getToken(),
        props: props,
        labels: labels
      }

      const baseURL = process.env.VUE_APP_BASE_API
      const qs = Object.keys(params)
        .map(key => `${key}=${params[key]}`)
        .join('&');

      window.location.href = baseURL + path + "?" + qs;
    },

    validInput() {
      if (this.queryParams.deviceId === "" || this.queryParams.deviceId === undefined
        || this.queryParams.deviceId === null) {
        this.$message({
          showClose: true,
          duration: 1000,
          message: this.$t('query.inputDeviceNumber'),
          type: 'warning'
        });
        return false;
      }

      if (this.dateRange.length !== 2) {
        this.$message({
          showClose: true,
          duration: 1000,
          message: this.$t('query.selectTimeRange'),
          type: 'warning'
        });
        return false;
      }
      return true;
    },
  }

}
</script>

<style scoped>
.el-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}
</style>
